<template>
	<div>
		<div id="stores_map" style="width: 100px;height: 100px;">
			
		</div>
	</div>
</template>

<script>
    import axios from 'axios';
    import { STORE_DISTANCE } from '../../config/postMessage-types.js';
	export default {
		props:{
			
		},
		data(){
			return {
				stores:[],
				img:null,
				lat:null, //当前位置纬度
				lng:null,  //当前位置经度,
				storeDistance: '',
                myMap:null,
                isError:0 //0 定位成功  1 定位失败 2 未获取到门店信息
			}
		},
		components:{
		},
		methods: {
            //发送消息到RN
            sendMessage(){
                var RnParams = {
                    type: STORE_DISTANCE,
                    params: {
                        isError: this.isError,
                        storeDistance: this.storeDistance,
                        lat: this.lat,
                        lng:this.lng
                    }
                }
                window.postMessage(JSON.stringify(RnParams));
            },
			getStores(){
				var url = window.api.base_host + "/baseStore/getRestStore"
				var params = {
					enterprisecode:window.api.enterprisecode
				}
				var config = {
					url:url,
					methods:"GET",
					params,
				}
				axios(config).then((res)=>{
					if(res.data.returnCode == 1){
						this.stores = res.data.data[0];
					}
				})
			},
			//根据高德地图 计算与门店之间的距离
			getDistanceAgain(item, index){
				var arr = [];
				if(item.positionLng){
					arr.push(Number(item.positionLng));
					arr.push(Number(item.positionLat));
				}
				var myDistance = null;
				var that = this;
                var lnglat = new AMap.LngLat(this.lng,this.lat);
                
				console.log((lnglat.distance(arr))/1000,'两点之间的距离');
                myDistance = (lnglat.distance(arr))/1000 ;
                
				if(myDistance=='Infinity'){
                    that.storeDistance[index] ='';
                    that.isError = 1; // 定位失败
				}else{
					that.storeDistance = Number(myDistance).toFixed(2);
                }
                this.sendMessage();
			},
			initMap(){
				//创建地图
				var that = this;
				this.myMap = new AMap.Map('stores_map', {
					zoom: 16,
					center: [116.397428, 39.90923], //new AMap.LngLat(116.39,39.9)
					resizeEnable: true,
					scrollWheel: true
				});
				//地图定位，获取当前位置的经纬度
				this.myMap.plugin(['AMap.Geolocation','AMap.LngLat'],function(){
					var userGeolocation = new AMap.Geolocation({
						enableHighAccuracy: true, //是否使用高精度定位，默认:true
						timeout: 10000, //超过10秒后停止定位，默认：无穷大
						maximumAge: 0 //定位结果缓存0毫秒，默认：0
					})
					console.log(userGeolocation,'dingwei對象')
					console.log(that.myMap,'地圖對象')
					that.myMap.addControl(userGeolocation);
					userGeolocation.getCurrentPosition();
					AMap.event.addListener(userGeolocation, 'complete', function(result) {
						console.log(result, '定位成功返回结果');
						//存经纬度信息
						that.lng = result.position.lng;
						that.lat = result.position.lat;
                    }); //返回定位信息
                    AMap.event.addListener(userGeolocation, 'error', function(result) {
                        console.log('定位失败');
                        that.isError = 1;
                        that.sendMessage();
					}); 
					
				})	
			},
			initScript() {
				//判断如果有script就删掉
				if (document.querySelector("#amap-box")){
					document.body.removeChild(document.querySelector("#amap-box"));
				}
				let amapBox = document.createElement("div");
				amapBox.setAttribute("id", "amap-box");
	
				let script1 = document.createElement("script");
				script1.onload = () => {
					console.log("地图加载完毕");
					let script2 = document.createElement("script");
					script2.onload = () => {
                        console.log("script2加载完毕");
                        setTimeout(() => {
                            this.initMap();
                        },500)
					}
					script2.src = "//webapi.amap.com/ui/1.0/main.js";
					amapBox.insertAdjacentElement("beforeend", script2);
				};
				script1.src = "https://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba";
				amapBox.insertAdjacentElement("beforeend", script1);
				document.body.appendChild(amapBox);
			},
		},
		watch: {
			lng(newVal,oldVal){
				if (Array.isArray(this.stores) && this.stores.length) {
					this.stores.forEach((item, index) => {
                        if(item.storeCode == window.api.storeCode){
                            this.getDistanceAgain(item, index);
                        }
					});
				}
			}
		},
		mounted(){
			this.initScript();
		},
		created(){
			this.getStores();
		},
		beforeDestory(){
			// 处理抖动问题
			if(document.querySelectorAll(".amap-sug-result")){
				document.querySelector("body").removeChild(document.querySelectorAll(".amap-sug-result"));
			}
		},
	}
</script>

<style scoped="scoped">
	
</style>
